home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / greps.zip / DFA.C < prev    next >
C/C++ Source or Header  |  1993-09-17  |  60KB  |  2,276 lines

  1. /* dfa.c - determinisitic extended regexp routines for GNU
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written June, 1988 by Mike Haertel
  19.    Modified July, 1988 by Arthur David Olson to assist BMG speedups  */
  20.  
  21. #include <stdio.h>
  22. #include <assert.h>
  23.  
  24. #if defined(USG) || defined(STDC_HEADERS)
  25. #include <string.h>
  26. #ifndef index
  27. #define index strchr
  28. #endif
  29. #else
  30. #include <string.h>
  31. #endif
  32.  
  33. #include "dfa.h"
  34.  
  35. #if __STDC__
  36. typedef void *ptr_t;
  37. #else
  38. typedef char *ptr_t;
  39. #endif
  40.  
  41. static void    regmust();
  42.  
  43. static ptr_t
  44. xcalloc(n, s)
  45.      int n;
  46.      size_t s;
  47. {
  48.   ptr_t r = calloc(n, s);
  49.  
  50.   if (!r)
  51.     regerror("Memory exhausted");
  52.   return r;
  53. }
  54.  
  55. ptr_t                /* Not static, so alloca.o can use it.  */
  56. xmalloc(n)
  57.      size_t n;
  58. {
  59.   ptr_t r = malloc(n);
  60.  
  61.   assert(n != 0);
  62.   if (!r)
  63.     regerror("Memory exhausted");
  64.   return r;
  65. }
  66.  
  67. static ptr_t
  68. xrealloc(p, n)
  69.      ptr_t p;
  70.      size_t n;
  71. {
  72.   ptr_t r = realloc(p, n);
  73.  
  74.   assert(n != 0);
  75.   if (!r)
  76.     regerror("Memory exhausted");
  77.   return r;
  78. }
  79.  
  80. #define CALLOC(p, t, n) ((p) = (t *) xcalloc((n), sizeof (t)))
  81. #define MALLOC(p, t, n) ((p) = (t *) xmalloc((n) * sizeof (t)))
  82. #define REALLOC(p, t, n) ((p) = (t *) xrealloc((ptr_t) (p), (n) * sizeof (t)))
  83.  
  84. /* Reallocate an array of type t if nalloc is too small for index. */
  85. #define REALLOC_IF_NECESSARY(p, t, nalloc, index) \
  86.   if ((index) >= (nalloc))              \
  87.     {                          \
  88.       while ((index) >= (nalloc))          \
  89.     (nalloc) *= 2;                  \
  90.       REALLOC(p, t, nalloc);              \
  91.     }
  92.  
  93. #ifdef DEBUG
  94. #include <stdio.h>
  95.  
  96. static void
  97. prtok(t)
  98.      _token t;
  99. {
  100.   char *s;
  101.  
  102.   if (t < 0)
  103.     fprintf(stderr, "END");
  104.   else if (t < _NOTCHAR)
  105.     fprintf(stderr, "%c", t);
  106.   else
  107.     {
  108.       switch (t)
  109.     {
  110.     case _EMPTY: s = "EMPTY"; break;
  111.     case _BACKREF: s = "BACKREF"; break;
  112.     case _BEGLINE: s = "BEGLINE"; break;
  113.     case _ALLBEGLINE: s = "ALLBEGLINE"; break;
  114.     case _ENDLINE: s = "ENDLINE"; break;
  115.     case _ALLENDLINE: s = "ALLENDLINE"; break;
  116.     case _BEGWORD: s = "BEGWORD"; break;
  117.     case _ENDWORD: s = "ENDWORD"; break;
  118.     case _LIMWORD: s = "LIMWORD"; break;
  119.     case _NOTLIMWORD: s = "NOTLIMWORD"; break;
  120.     case _QMARK: s = "QMARK"; break;
  121.     case _STAR: s = "STAR"; break;
  122.     case _PLUS: s = "PLUS"; break;
  123.     case _CAT: s = "CAT"; break;
  124.     case _OR: s = "OR"; break;
  125.     case _LPAREN: s = "LPAREN"; break;
  126.     case _RPAREN: s = "RPAREN"; break;
  127.     default: s = "SET"; break;
  128.     }
  129.       fprintf(stderr, "%s", s);
  130.     }
  131. }
  132. #endif /* DEBUG */
  133.  
  134. /* Stuff pertaining to charsets. */
  135.  
  136. static int
  137. tstbit(b, c)
  138.      int b;
  139.      _charset c;
  140. {
  141.   return c[b / INTBITS] & 1 << b % INTBITS;
  142. }
  143.  
  144. static void
  145. setbit(b, c)
  146.      int b;
  147.      _charset c;
  148. {
  149.   c[b / INTBITS] |= 1 << b % INTBITS;
  150. }
  151.  
  152. static void
  153. clrbit(b, c)
  154.      int b;
  155.      _charset c;
  156. {
  157.   c[b / INTBITS] &= ~(1 << b % INTBITS);
  158. }
  159.  
  160. static void
  161. copyset(src, dst)
  162.      const _charset src;
  163.      _charset dst;
  164. {
  165.   int i;
  166.  
  167.   for (i = 0; i < _CHARSET_INTS; ++i)
  168.     dst[i] = src[i];
  169. }
  170.  
  171. static void
  172. zeroset(s)
  173.      _charset s;
  174. {
  175.   int i;
  176.  
  177.   for (i = 0; i < _CHARSET_INTS; ++i)
  178.     s[i] = 0;
  179. }
  180.  
  181. static void
  182. notset(s)
  183.      _charset s;
  184. {
  185.   int i;
  186.  
  187.   for (i = 0; i < _CHARSET_INTS; ++i)
  188.     s[i] = ~s[i];
  189. }
  190.  
  191. static int
  192. equal(s1, s2)
  193.      const _charset s1;
  194.      const _charset s2;
  195. {
  196.   int i;
  197.  
  198.   for (i = 0; i < _CHARSET_INTS; ++i)
  199.     if (s1[i] != s2[i])
  200.       return 0;
  201.   return 1;
  202. }
  203.  
  204. /* A pointer to the current regexp is kept here during parsing. */
  205. static struct regexp *reg;
  206.  
  207. /* Find the index of charset s in reg->charsets, or allocate a new charset. */
  208. static int
  209. charset_index(s)
  210.      const _charset s;
  211. {
  212.   int i;
  213.  
  214.   for (i = 0; i < reg->cindex; ++i)
  215.     if (equal(s, reg->charsets[i]))
  216.       return i;
  217.   REALLOC_IF_NECESSARY(reg->charsets, _charset, reg->calloc, reg->cindex);
  218.   ++reg->cindex;
  219.   copyset(s, reg->charsets[i]);
  220.   return i;
  221. }
  222.  
  223. /* Syntax bits controlling the behavior of the lexical analyzer. */
  224. static syntax_bits, syntax_bits_set;
  225.  
  226. /* Flag for case-folding letters into sets. */
  227. static case_fold;
  228.  
  229. /* Entry point to set syntax options. */
  230. void
  231. regsyntax(bits, fold)
  232.      int bits;
  233.      int fold;
  234. {
  235.   syntax_bits_set = 1;
  236.   syntax_bits = bits;
  237.   case_fold = fold;
  238. }
  239.  
  240. /* Lexical analyzer. */
  241. static const char *lexstart;    /* Pointer to beginning of input string. */
  242. static const char *lexptr;    /* Pointer to next input character. */
  243. static lexleft;            /* Number of characters remaining. */
  244. static caret_allowed;        /* True if backward context allows ^
  245.                    (meaningful only if RE_CONTEXT_INDEP_OPS
  246.                    is turned off). */
  247. static closure_allowed;        /* True if backward context allows closures
  248.                    (meaningful only if RE_CONTEXT_INDEP_OPS
  249.                    is turned off). */
  250.  
  251. /* Note that characters become unsigned here. */
  252. #define FETCH(c, eoferr)             \
  253.   {                         \
  254.     if (! lexleft)                 \
  255.       if (eoferr)                 \
  256.     regerror(eoferr);            \
  257.       else                     \
  258.     return _END;                 \
  259.     (c) = (unsigned char) *lexptr++;  \
  260.     --lexleft;                     \
  261.   }
  262.  
  263. static _token
  264. lex()
  265. {
  266.   _token c, c2;
  267.   int invert;
  268.   _charset cset;
  269.  
  270.   FETCH(c, (char *) 0);
  271.   switch (c)
  272.     {
  273.     case '^':
  274.       if (! (syntax_bits & RE_CONTEXT_INDEP_OPS)
  275.       && (!caret_allowed ||
  276.           (syntax_bits & RE_TIGHT_VBAR) && lexptr - 1 != lexstart))
  277.     goto normal_char;
  278.       caret_allowed = 0;
  279.       return syntax_bits & RE_TIGHT_VBAR ? _ALLBEGLINE : _BEGLINE;
  280.  
  281.     case '$':
  282.       if (syntax_bits & RE_CONTEXT_INDEP_OPS || !lexleft
  283.       || (! (syntax_bits & RE_TIGHT_VBAR)
  284.           && ((syntax_bits & RE_NO_BK_PARENS
  285.            ? lexleft > 0 && *lexptr == ')'
  286.            : lexleft > 1 && *lexptr == '\\' && lexptr[1] == ')')
  287.           || (syntax_bits & RE_NO_BK_VBAR
  288.               ? lexleft > 0 && *lexptr == '|'
  289.               : lexleft > 1 && *lexptr == '\\' && lexptr[1] == '|'))))
  290.     return syntax_bits & RE_TIGHT_VBAR ? _ALLENDLINE : _ENDLINE;
  291.       goto normal_char;
  292.  
  293.     case '\\':
  294.       FETCH(c, "Unfinished \\ quote");
  295.       switch (c)
  296.     {
  297.     case '1':
  298.     case '2':
  299.     case '3':
  300.     case '4':
  301.     case '5':
  302.     case '6':
  303.     case '7':
  304.     case '8':
  305.     case '9':
  306.       caret_allowed = 0;
  307.       closure_allowed = 1;
  308.       return _BACKREF;
  309.  
  310.     case '<':
  311.       caret_allowed = 0;
  312.       return _BEGWORD;
  313.  
  314.     case '>':
  315.       caret_allowed = 0;
  316.       return _ENDWORD;
  317.  
  318.     case 'b':
  319.       caret_allowed = 0;
  320.       return _LIMWORD;
  321.  
  322.     case 'B':
  323.       caret_allowed = 0;
  324.       return _NOTLIMWORD;
  325.  
  326.     case 'w':
  327.     case 'W':
  328.       zeroset(cset);
  329.       for (c2 = 0; c2 < _NOTCHAR; ++c2)
  330.         if (ISALNUM(c2))
  331.           setbit(c2, cset);
  332.       if (c == 'W')
  333.         notset(cset);
  334.       caret_allowed = 0;
  335.       closure_allowed = 1;
  336.       return _SET + charset_index(cset);
  337.  
  338.     case '?':
  339.       if (syntax_bits & RE_BK_PLUS_QM)
  340.         goto qmark;
  341.       goto normal_char;
  342.  
  343.     case '+':
  344.       if (syntax_bits & RE_BK_PLUS_QM)
  345.         goto plus;
  346.       goto normal_char;
  347.  
  348.     case '|':
  349.       if (! (syntax_bits & RE_NO_BK_VBAR))
  350.         goto or;
  351.       goto normal_char;
  352.  
  353.     case '(':
  354.       if (! (syntax_bits & RE_NO_BK_PARENS))
  355.         goto lparen;
  356.       goto normal_char;
  357.  
  358.     case ')':
  359.       if (! (syntax_bits & RE_NO_BK_PARENS))
  360.         goto rparen;
  361.       goto normal_char;
  362.  
  363.     default:
  364.       goto normal_char;
  365.     }
  366.  
  367.     case '?':
  368.       if (syntax_bits & RE_BK_PLUS_QM)
  369.     goto normal_char;
  370.     qmark:
  371.       if (! (syntax_bits & RE_CONTEXT_INDEP_OPS) && !closure_allowed)
  372.     goto normal_char;
  373.       return _QMARK;
  374.  
  375.     case '*':
  376.       if (! (syntax_bits & RE_CONTEXT_INDEP_OPS) && !closure_allowed)
  377.     goto normal_char;
  378.       return _STAR;
  379.  
  380.     case '+':
  381.       if (syntax_bits & RE_BK_PLUS_QM)
  382.     goto normal_char;
  383.     plus:
  384.       if (! (syntax_bits & RE_CONTEXT_INDEP_OPS) && !closure_allowed)
  385.     goto normal_char;
  386.       return _PLUS;
  387.  
  388.     case '|':
  389.       if (! (syntax_bits & RE_NO_BK_VBAR))
  390.     goto normal_char;
  391.     or:
  392.       caret_allowed = 1;
  393.       closure_allowed = 0;
  394.       return _OR;
  395.  
  396.     case '\n':
  397.       if (! (syntax_bits & RE_NEWLINE_OR))
  398.     goto normal_char;
  399.       goto or;
  400.  
  401.     case '(':
  402.       if (! (syntax_bits & RE_NO_BK_PARENS))
  403.     goto normal_char;
  404.     lparen:
  405.       caret_allowed = 1;
  406.       closure_allowed = 0;
  407.       return _LPAREN;
  408.  
  409.     case ')':
  410.       if (! (syntax_bits & RE_NO_BK_PARENS))
  411.     goto normal_char;
  412.     rparen:
  413.       caret_allowed = 0;
  414.       closure_allowed = 1;
  415.       return _RPAREN;
  416.  
  417.     case '.':
  418.       zeroset(cset);
  419.       notset(cset);
  420.       clrbit('\n', cset);
  421.       caret_allowed = 0;
  422.       closure_allowed = 1;
  423.       return _SET + charset_index(cset);
  424.  
  425.     case '[':
  426.       zeroset(cset);
  427.       FETCH(c, "Unbalanced [");
  428.       if (c == '^')
  429.     {
  430.       FETCH(c, "Unbalanced [");
  431.       invert = 1;
  432.     }
  433.       else
  434.     invert = 0;
  435.       do
  436.     {
  437.       FETCH(c2, "Unbalanced [");
  438.       if (c2 == '-')
  439.         {
  440.           FETCH(c2, "Unbalanced [");
  441.           while (c <= c2)
  442.         {
  443.           setbit(c, cset);
  444.           if (case_fold)
  445.             if (ISUPPER(c))
  446.               setbit(tolower(c), cset);
  447.             else if (ISLOWER(c))
  448.               setbit(toupper(c), cset);
  449.           ++c;
  450.         }
  451.           FETCH(c, "Unbalanced [");
  452.         }
  453.       else
  454.         {
  455.           setbit(c, cset);
  456.           if (case_fold)
  457.         if (ISUPPER(c))
  458.           setbit(tolower(c), cset);
  459.         else if (ISLOWER(c))
  460.           setbit(toupper(c), cset);
  461.           c = c2;
  462.         }
  463.     }
  464.       while (c != ']');
  465.       if (invert)
  466.     notset(cset);
  467.       caret_allowed = 0;
  468.       closure_allowed = 1;
  469.       return _SET + charset_index(cset);
  470.  
  471.     default:
  472.     normal_char:
  473.       caret_allowed = 0;
  474.       closure_allowed = 1;
  475.       if (case_fold && ISALPHA(c))
  476.     {
  477.       zeroset(cset);
  478.       if (isupper(c))
  479.         c = tolower(c);
  480.       setbit(c, cset);
  481.       setbit(toupper(c), cset);
  482.       return _SET + charset_index(cset);
  483.     }
  484.       return c;
  485.     }
  486. }
  487.  
  488. /* Recursive descent parser for regular expressions. */
  489.  
  490. static _token tok;        /* Lookahead token. */
  491. static depth;            /* Current depth of a hypothetical stack
  492.                    holding deferred productions.  This is
  493.                    used to determine the depth that will be
  494.                    required of the real stack later on in
  495.                    reganalyze(). */
  496.  
  497. /* Add the given token to the parse tree, maintaining the depth count and
  498.    updating the maximum depth if necessary. */
  499. static void
  500. addtok(t)
  501.      _token t;
  502. {
  503.   REALLOC_IF_NECESSARY(reg->tokens, _token, reg->talloc, reg->tindex);
  504.   reg->tokens[reg->tindex++] = t;
  505.  
  506.   switch (t)
  507.     {
  508.     case _QMARK:
  509.     case _STAR:
  510.     case _PLUS:
  511.       break;
  512.  
  513.     case _CAT:
  514.     case _OR:
  515.       --depth;
  516.       break;
  517.  
  518.     default:
  519.       ++reg->nleaves;
  520.     case _EMPTY:
  521.       ++depth;
  522.       break;
  523.     }
  524.   if (depth > reg->depth)
  525.     reg->depth = depth;
  526. }
  527.  
  528. /* The grammar understood by the parser is as follows.
  529.  
  530.    start:
  531.      regexp
  532.      _ALLBEGLINE regexp
  533.      regexp _ALLENDLINE
  534.      _ALLBEGLINE regexp _ALLENDLINE
  535.  
  536.    regexp:
  537.      regexp _OR branch
  538.      branch
  539.  
  540.    branch:
  541.      branch closure
  542.      closure
  543.  
  544.    closure:
  545.      closure _QMARK
  546.      closure _STAR
  547.      closure _PLUS
  548.      atom
  549.  
  550.    atom:
  551.      <normal character>
  552.      _SET
  553.      _BACKREF
  554.      _BEGLINE
  555.      _ENDLINE
  556.      _BEGWORD
  557.      _ENDWORD
  558.      _LIMWORD
  559.      _NOTLIMWORD
  560.      <empty>
  561.  
  562.    The parser builds a parse tree in postfix form in an array of tokens. */
  563.  
  564. #if __STDC__
  565. static void regexp(void);
  566. #else
  567. static void regexp();
  568. #endif
  569.  
  570. static void
  571. atom()
  572. {
  573.   if (tok >= 0 && tok < _NOTCHAR || tok >= _SET || tok == _BACKREF
  574.       || tok == _BEGLINE || tok == _ENDLINE || tok == _BEGWORD
  575.       || tok == _ENDWORD || tok == _LIMWORD || tok == _NOTLIMWORD)
  576.     {
  577.       addtok(tok);
  578.       tok = lex();
  579.     }
  580.   else if (tok == _LPAREN)
  581.     {
  582.       tok = lex();
  583.       regexp();
  584.       if (tok != _RPAREN)
  585.     regerror("Unbalanced (");
  586.       tok = lex();
  587.     }
  588.   else
  589.     addtok(_EMPTY);
  590. }
  591.  
  592. static void
  593. closure()
  594. {
  595.   atom();
  596.   while (tok == _QMARK || tok == _STAR || tok == _PLUS)
  597.     {
  598.       addtok(tok);
  599.       tok = lex();
  600.     }
  601. }
  602.  
  603. static void
  604. branch()
  605. {
  606.   closure();
  607.   while (tok != _RPAREN && tok != _OR && tok != _ALLENDLINE && tok >= 0)
  608.     {
  609.       closure();
  610.       addtok(_CAT);
  611.     }
  612. }
  613.  
  614. static void
  615. regexp()
  616. {
  617.   branch();
  618.   while (tok == _OR)
  619.     {
  620.       tok = lex();
  621.       branch();
  622.       addtok(_OR);
  623.     }
  624. }
  625.  
  626. /* Main entry point for the parser.  S is a string to be parsed, len is the
  627.    length of the string, so s can include NUL characters.  R is a pointer to
  628.    the struct regexp to parse into. */
  629. void
  630. regparse(s, len, r)
  631.      const char *s;
  632.      size_t len;
  633.      struct regexp *r;
  634. {
  635.   reg = r;
  636.   lexstart = lexptr = s;
  637.   lexleft = len;
  638.   caret_allowed = 1;
  639.   closure_allowed = 0;
  640.  
  641.   if (! syntax_bits_set)
  642.     regerror("No syntax specified");
  643.  
  644.   tok = lex();
  645.   depth = r->depth;
  646.  
  647.   if (tok == _ALLBEGLINE)
  648.     {
  649.       addtok(_BEGLINE);
  650.       tok = lex();
  651.       regexp();
  652.       addtok(_CAT);
  653.     }
  654.   else
  655.     regexp();
  656.  
  657.   if (tok == _ALLENDLINE)
  658.     {
  659.       addtok(_ENDLINE);
  660.       addtok(_CAT);
  661.       tok = lex();
  662.     }
  663.  
  664.   if (tok != _END)
  665.     regerror("Unbalanced )");
  666.  
  667.   addtok(_END - r->nregexps);
  668.   addtok(_CAT);
  669.  
  670.   if (r->nregexps)
  671.     addtok(_OR);
  672.  
  673.   ++r->nregexps;
  674. }
  675.  
  676. /* Some primitives for operating on sets of positions. */
  677.  
  678. /* Copy one set to another; the destination must be large enough. */
  679. static void
  680. copy(src, dst)
  681.      const _position_set *src;
  682.      _position_set *dst;
  683. {
  684.   int i;
  685.  
  686.   for (i = 0; i < src->nelem; ++i)
  687.     dst->elems[i] = src->elems[i];
  688.   dst->nelem = src->nelem;
  689. }
  690.  
  691. /* Insert a position in a set.  Position sets are maintained in sorted
  692.    order according to index.  If position already exists in the set with
  693.    the same index then their constraints are logically or'd together.
  694.    S->elems must point to an array large enough to hold the resulting set. */
  695. static void
  696. insert(p, s)
  697.      _position p;
  698.      _position_set *s;
  699. {
  700.   int i;
  701.   _position t1, t2;
  702.  
  703.   for (i = 0; i < s->nelem && p.index < s->elems[i].index; ++i)
  704.     ;
  705.   if (i < s->nelem && p.index == s->elems[i].index)
  706.     s->elems[i].constraint |= p.constraint;
  707.   else
  708.     {
  709.       t1 = p;
  710.       ++s->nelem;
  711.       while (i < s->nelem)
  712.     {
  713.       t2 = s->elems[i];
  714.       s->elems[i++] = t1;
  715.       t1 = t2;
  716.     }
  717.     }
  718. }
  719.  
  720. /* Merge two sets of positions into a third.  The result is exactly as if
  721.    the positions of both sets were inserted into an initially empty set. */
  722. static void
  723. merge(s1, s2, m)
  724.      _position_set *s1;
  725.      _position_set *s2;
  726.      _position_set *m;
  727. {
  728.   int i = 0, j = 0;
  729.  
  730.   m->nelem = 0;
  731.   while (i < s1->nelem && j < s2->nelem)
  732.     if (s1->elems[i].index > s2->elems[j].index)
  733.       m->elems[m->nelem++] = s1->elems[i++];
  734.     else if (s1->elems[i].index < s2->elems[j].index)
  735.       m->elems[m->nelem++] = s2->elems[j++];
  736.     else
  737.       {
  738.     m->elems[m->nelem] = s1->elems[i++];
  739.     m->elems[m->nelem++].constraint |= s2->elems[j++].constraint;
  740.       }
  741.   while (i < s1->nelem)
  742.     m->elems[m->nelem++] = s1->elems[i++];
  743.   while (j < s2->nelem)
  744.     m->elems[m->nelem++] = s2->elems[j++];
  745. }
  746.  
  747. /* Delete a position from a set. */
  748. static void
  749. delete(p, s)
  750.      _position p;
  751.      _position_set *s;
  752. {
  753.   int i;
  754.  
  755.   for (i = 0; i < s->nelem; ++i)
  756.     if (p.index == s->elems[i].index)
  757.       break;
  758.   if (i < s->nelem)
  759.     for (--s->nelem; i < s->nelem; ++i)
  760.       s->elems[i] = s->elems[i + 1];
  761. }
  762.  
  763. /* Find the index of the state corresponding to the given position set with
  764.    the given preceding context, or create a new state if there is no such
  765.    state.  Newline and letter tell whether we got here on a newline or
  766.    letter, respectively. */
  767. static int
  768. state_index(r, s, newline, letter)
  769.      struct regexp *r;
  770.      _position_set *s;
  771.      int newline;
  772.      int letter;
  773. {
  774.   int hash = 0;
  775.   int constraint;
  776.   int i, j;
  777.  
  778.   newline = newline ? 1 : 0;
  779.   letter = letter ? 1 : 0;
  780.  
  781.   for (i = 0; i < s->nelem; ++i)
  782.     hash ^= s->elems[i].index + s->elems[i].constraint;
  783.  
  784.   /* Try to find a state that exactly matches the proposed one. */
  785.   for (i = 0; i < r->sindex; ++i)
  786.     {
  787.       if (hash != r->states[i].hash || s->nelem != r->states[i].elems.nelem
  788.       || newline != r->states[i].newline || letter != r->states[i].letter)
  789.     continue;
  790.       for (j = 0; j < s->nelem; ++j)
  791.     if (s->elems[j].constraint
  792.         != r->states[i].elems.elems[j].constraint
  793.         || s->elems[j].index != r->states[i].elems.elems[j].index)
  794.       break;
  795.       if (j == s->nelem)
  796.     return i;
  797.     }
  798.  
  799.   /* We'll have to create a new state. */
  800.   REALLOC_IF_NECESSARY(r->states, _dfa_state, r->salloc, r->sindex);
  801.   r->states[i].hash = hash;
  802.   MALLOC(r->states[i].elems.elems, _position, s->nelem);
  803.   copy(s, &r->states[i].elems);
  804.   r->states[i].newline = newline;
  805.   r->states[i].letter = letter;
  806.   r->states[i].backref = 0;
  807.   r->states[i].constraint = 0;
  808.   r->states[i].first_end = 0;
  809.   for (j = 0; j < s->nelem; ++j)
  810.     if (r->tokens[s->elems[j].index] < 0)
  811.       {
  812.     constraint = s->elems[j].constraint;
  813.     if (_SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 0)
  814.         || _SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 1)
  815.         || _SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 0)
  816.         || _SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 1))
  817.       r->states[i].constraint |= constraint;
  818.     if (! r->states[i].first_end)
  819.       r->states[i].first_end = r->tokens[s->elems[j].index];
  820.       }
  821.     else if (r->tokens[s->elems[j].index] == _BACKREF)
  822.       {
  823.     r->states[i].constraint = _NO_CONSTRAINT;
  824.     r->states[i].backref = 1;
  825.       }
  826.  
  827.   ++r->sindex;
  828.  
  829.   return i;
  830. }
  831.  
  832. /* Find the epsilon closure of a set of positions.  If any position of the set
  833.    contains a symbol that matches the empty string in some context, replace
  834.    that position with the elements of its follow labeled with an appropriate
  835.    constraint.  Repeat exhaustively until no funny positions are left.
  836.    S->elems must be large enough to hold the result. */
  837. void
  838. epsclosure(s, r)
  839.      _position_set *s;
  840.      struct regexp *r;
  841. {
  842.   int i, j;
  843.   int *visited;
  844.   _position p, old;
  845.  
  846.   MALLOC(visited, int, r->tindex);
  847.   for (i = 0; i < r->tindex; ++i)
  848.     visited[i] = 0;
  849.  
  850.   for (i = 0; i < s->nelem; ++i)
  851.     if (r->tokens[s->elems[i].index] >= _NOTCHAR
  852.     && r->tokens[s->elems[i].index] != _BACKREF
  853.     && r->tokens[s->elems[i].index] < _SET)
  854.       {
  855.     old = s->elems[i];
  856.     p.constraint = old.constraint;
  857.     delete(s->elems[i], s);
  858.     if (visited[old.index])
  859.       {
  860.         --i;
  861.         continue;
  862.       }
  863.     visited[old.index] = 1;
  864.     switch (r->tokens[old.index])
  865.       {
  866.       case _BEGLINE:
  867.         p.constraint &= _BEGLINE_CONSTRAINT;
  868.         break;
  869.       case _ENDLINE:
  870.         p.constraint &= _ENDLINE_CONSTRAINT;
  871.         break;
  872.       case _BEGWORD:
  873.         p.constraint &= _BEGWORD_CONSTRAINT;
  874.         break;
  875.       case _ENDWORD:
  876.         p.constraint &= _ENDWORD_CONSTRAINT;
  877.         break;
  878.       case _LIMWORD:
  879.         p.constraint &= _LIMWORD_CONSTRAINT;
  880.         break;
  881.       case _NOTLIMWORD:
  882.         p.constraint &= _NOTLIMWORD_CONSTRAINT;
  883.         break;
  884.       default:
  885.         break;
  886.       }
  887.     for (j = 0; j < r->follows[old.index].nelem; ++j)
  888.       {
  889.         p.index = r->follows[old.index].elems[j].index;
  890.         insert(p, s);
  891.       }
  892.     /* Force rescan to start at the beginning. */
  893.     i = -1;
  894.       }
  895.  
  896.   free(visited);
  897. }
  898.  
  899. /* Perform bottom-up analysis on the parse tree, computing various functions.
  900.    Note that at this point, we're pretending constructs like \< are real
  901.    characters rather than constraints on what can follow them.
  902.  
  903.    Nullable:  A node is nullable if it is at the root of a regexp that can
  904.    match the empty string.
  905.    *  _EMPTY leaves are nullable.
  906.    * No other leaf is nullable.
  907.    * A _QMARK or _STAR node is nullable.
  908.    * A _PLUS node is nullable if its argument is nullable.
  909.    * A _CAT node is nullable if both its arguments are nullable.
  910.    * An _OR node is nullable if either argument is nullable.
  911.  
  912.    Firstpos:  The firstpos of a node is the set of positions (nonempty leaves)
  913.    that could correspond to the first character of a string matching the
  914.    regexp rooted at the given node.
  915.    * _EMPTY leaves have empty firstpos.
  916.    * The firstpos of a nonempty leaf is that leaf itself.
  917.    * The firstpos of a _QMARK, _STAR, or _PLUS node is the firstpos of its
  918.      argument.
  919.    * The firstpos of a _CAT node is the firstpos of the left argument, union
  920.      the firstpos of the right if the left argument is nullable.
  921.    * The firstpos of an _OR node is the union of firstpos of each argument.
  922.  
  923.    Lastpos:  The lastpos of a node is the set of positions that could
  924.    correspond to the last character of a string matching the regexp at
  925.    the given node.
  926.    * _EMPTY leaves have empty lastpos.
  927.    * The lastpos of a nonempty leaf is that leaf itself.
  928.    * The lastpos of a _QMARK, _STAR, or _PLUS node is the lastpos of its
  929.      argument.
  930.    * The lastpos of a _CAT node is the lastpos of its right argument, union
  931.      the lastpos of the left if the right argument is nullable.
  932.    * The lastpos of an _OR node is the union of the lastpos of each argument.
  933.  
  934.    Follow:  The follow of a position is the set of positions that could
  935.    correspond to the character following a character matching the node in
  936.    a string matching the regexp.  At this point we consider special symbols
  937.    that match the empty string in some context to be just normal characters.
  938.    Later, if we find that a special symbol is in a follow set, we will
  939.    replace it with the elements of its follow, labeled with an appropriate
  940.    constraint.
  941.    * Every node in the firstpos of the argument of a _STAR or _PLUS node is in
  942.      the follow of every node in the lastpos.
  943.    * Every node in the firstpos of the second argument of a _CAT node is in
  944.      the follow of every node in the lastpos of the first argument.
  945.  
  946.    Because of the postfix representation of the parse tree, the depth-first
  947.    analysis is conveniently done by a linear scan with the aid of a stack.
  948.    Sets are stored as arrays of the elements, obeying a stack-like allocation
  949.    scheme; the number of elements in each set deeper in the stack can be
  950.    used to determine the address of a particular set's array. */
  951. void
  952. reganalyze(r, searchflag)
  953.      struct regexp *r;
  954.      int searchflag;
  955. {
  956.   int *nullable;        /* Nullable stack. */
  957.   int *nfirstpos;        /* Element count stack for firstpos sets. */
  958.   _position *firstpos;        /* Array where firstpos elements are stored. */
  959.   int *nlastpos;        /* Element count stack for lastpos sets. */
  960.   _position *lastpos;        /* Array where lastpos elements are stored. */
  961.   int *nalloc;            /* Sizes of arrays allocated to follow sets. */
  962.   _position_set tmp;        /* Temporary set for merging sets. */
  963.   _position_set merged;        /* Result of merging sets. */
  964.   int wants_newline;        /* True if some position wants newline info. */
  965.   int *o_nullable;
  966.   int *o_nfirst, *o_nlast;
  967.   _position *o_firstpos, *o_lastpos;
  968.   int i, j;
  969.   _position *pos;
  970.  
  971. #ifdef DEBUG
  972.   fprintf(stderr, "reganalyze:\n");
  973.   for (i = 0; i < r->tindex; ++i)
  974.     {
  975.       fprintf(stderr, " %d:", i);
  976.       prtok(r->tokens[i]);
  977.     }
  978.   putc('\n', stderr);
  979. #endif
  980.  
  981.   r->searchflag = searchflag;
  982.  
  983.   MALLOC(nullable, int, r->depth);
  984.   o_nullable = nullable;
  985.   MALLOC(nfirstpos, int, r->depth);
  986.   o_nfirst = nfirstpos;
  987.   MALLOC(firstpos, _position, r->nleaves);
  988.   o_firstpos = firstpos, firstpos += r->nleaves;
  989.   MALLOC(nlastpos, int, r->depth);
  990.   o_nlast = nlastpos;
  991.   MALLOC(lastpos, _position, r->nleaves);
  992.   o_lastpos = lastpos, lastpos += r->nleaves;
  993.   MALLOC(nalloc, int, r->tindex);
  994.   for (i = 0; i < r->tindex; ++i)
  995.     nalloc[i] = 0;
  996.   MALLOC(merged.elems, _position, r->nleaves);
  997.  
  998.   CALLOC(r->follows, _position_set, r->tindex);
  999.  
  1000.   for (i = 0; i < r->tindex; ++i)
  1001. #ifdef DEBUG
  1002.     {                /* Nonsyntactic #ifdef goo... */
  1003. #endif
  1004.     switch (r->tokens[i])
  1005.       {
  1006.       case _EMPTY:
  1007.     /* The empty set is nullable. */
  1008.     *nullable++ = 1;
  1009.  
  1010.     /* The firstpos and lastpos of the empty leaf are both empty. */
  1011.     *nfirstpos++ = *nlastpos++ = 0;
  1012.     break;
  1013.  
  1014.       case _STAR:
  1015.       case _PLUS:
  1016.     /* Every element in the firstpos of the argument is in the follow
  1017.        of every element in the lastpos. */
  1018.     tmp.nelem = nfirstpos[-1];
  1019.     tmp.elems = firstpos;
  1020.     pos = lastpos;
  1021.     for (j = 0; j < nlastpos[-1]; ++j)
  1022.       {
  1023.         merge(&tmp, &r->follows[pos[j].index], &merged);
  1024.         REALLOC_IF_NECESSARY(r->follows[pos[j].index].elems, _position,
  1025.                  nalloc[pos[j].index], merged.nelem - 1);
  1026.         copy(&merged, &r->follows[pos[j].index]);
  1027.       }
  1028.  
  1029.       case _QMARK:
  1030.     /* A _QMARK or _STAR node is automatically nullable. */
  1031.     if (r->tokens[i] != _PLUS)
  1032.       nullable[-1] = 1;
  1033.     break;
  1034.  
  1035.       case _CAT:
  1036.     /* Every element in the firstpos of the second argument is in the
  1037.        follow of every element in the lastpos of the first argument. */
  1038.     tmp.nelem = nfirstpos[-1];
  1039.     tmp.elems = firstpos;
  1040.     pos = lastpos + nlastpos[-1];
  1041.     for (j = 0; j < nlastpos[-2]; ++j)
  1042.       {
  1043.         merge(&tmp, &r->follows[pos[j].index], &merged);
  1044.         REALLOC_IF_NECESSARY(r->follows[pos[j].index].elems, _position,
  1045.                  nalloc[pos[j].index], merged.nelem - 1);
  1046.         copy(&merged, &r->follows[pos[j].index]);
  1047.       }
  1048.  
  1049.     /* The firstpos of a _CAT node is the firstpos of the first argument,
  1050.        union that of the second argument if the first is nullable. */
  1051.     if (nullable[-2])
  1052.       nfirstpos[-2] += nfirstpos[-1];
  1053.     else
  1054.       firstpos += nfirstpos[-1];
  1055.     --nfirstpos;
  1056.  
  1057.     /* The lastpos of a _CAT node is the lastpos of the second argument,
  1058.        union that of the first argument if the second is nullable. */
  1059.     if (nullable[-1])
  1060.       nlastpos[-2] += nlastpos[-1];
  1061.     else
  1062.       {
  1063.         pos = lastpos + nlastpos[-2];
  1064.         for (j = nlastpos[-1] - 1; j >= 0; --j)
  1065.           pos[j] = lastpos[j];
  1066.         lastpos += nlastpos[-2];
  1067.         nlastpos[-2] = nlastpos[-1];
  1068.       }
  1069.     --nlastpos;
  1070.  
  1071.     /* A _CAT node is nullable if both arguments are nullable. */
  1072.     nullable[-2] = nullable[-1] && nullable[-2];
  1073.     --nullable;
  1074.     break;
  1075.  
  1076.       case _OR:
  1077.     /* The firstpos is the union of the firstpos of each argument. */
  1078.     nfirstpos[-2] += nfirstpos[-1];
  1079.     --nfirstpos;
  1080.  
  1081.     /* The lastpos is the union of the lastpos of each argument. */
  1082.     nlastpos[-2] += nlastpos[-1];
  1083.     --nlastpos;
  1084.  
  1085.     /* An _OR node is nullable if either argument is nullable. */
  1086.     nullable[-2] = nullable[-1] || nullable[-2];
  1087.     --nullable;
  1088.     break;
  1089.  
  1090.       default:
  1091.     /* Anything else is a nonempty position.  (Note that special
  1092.        constructs like \< are treated as nonempty strings here;
  1093.        an "epsilon closure" effectively makes them nullable later.
  1094.        Backreferences have to get a real position so we can detect
  1095.        transitions on them later.  But they are nullable. */
  1096.     *nullable++ = r->tokens[i] == _BACKREF;
  1097.  
  1098.     /* This position is in its own firstpos and lastpos. */
  1099.     *nfirstpos++ = *nlastpos++ = 1;
  1100.     --firstpos, --lastpos;
  1101.     firstpos->index = lastpos->index = i;
  1102.     firstpos->constraint = lastpos->constraint = _NO_CONSTRAINT;
  1103.  
  1104.     /* Allocate the follow set for this position. */
  1105.     nalloc[i] = 1;
  1106.     MALLOC(r->follows[i].elems, _position, nalloc[i]);
  1107.     break;
  1108.       }
  1109. #ifdef DEBUG
  1110.     /* ... balance the above nonsyntactic #ifdef goo... */
  1111.       fprintf(stderr, "node %d:", i);
  1112.       prtok(r->tokens[i]);
  1113.       putc('\n', stderr);
  1114.       fprintf(stderr, nullable[-1] ? " nullable: yes\n" : " nullable: no\n");
  1115.       fprintf(stderr, " firstpos:");
  1116.       for (j = nfirstpos[-1] - 1; j >= 0; --j)
  1117.     {
  1118.       fprintf(stderr, " %d:", firstpos[j].index);
  1119.       prtok(r->tokens[firstpos[j].index]);
  1120.     }
  1121.       fprintf(stderr, "\n lastpos:");
  1122.       for (j = nlastpos[-1] - 1; j >= 0; --j)
  1123.     {
  1124.       fprintf(stderr, " %d:", lastpos[j].index);
  1125.       prtok(r->tokens[lastpos[j].index]);
  1126.     }
  1127.       putc('\n', stderr);
  1128.     }
  1129. #endif
  1130.  
  1131.   /* For each follow set that is the follow set of a real position, replace
  1132.      it with its epsilon closure. */
  1133.   for (i = 0; i < r->tindex; ++i)
  1134.     if (r->tokens[i] < _NOTCHAR || r->tokens[i] == _BACKREF
  1135.     || r->tokens[i] >= _SET)
  1136.       {
  1137. #ifdef DEBUG
  1138.     fprintf(stderr, "follows(%d:", i);
  1139.     prtok(r->tokens[i]);
  1140.     fprintf(stderr, "):");
  1141.     for (j = r->follows[i].nelem - 1; j >= 0; --j)
  1142.       {
  1143.         fprintf(stderr, " %d:", r->follows[i].elems[j].index);
  1144.         prtok(r->tokens[r->follows[i].elems[j].index]);
  1145.       }
  1146.     putc('\n', stderr);
  1147. #endif
  1148.     copy(&r->follows[i], &merged);
  1149.     epsclosure(&merged, r);
  1150.     if (r->follows[i].nelem < merged.nelem)
  1151.       REALLOC(r->follows[i].elems, _position, merged.nelem);
  1152.     copy(&merged, &r->follows[i]);
  1153.       }
  1154.  
  1155.   /* Get the epsilon closure of the firstpos of the regexp.  The result will
  1156.      be the set of positions of state 0. */
  1157.   merged.nelem = 0;
  1158.   for (i = 0; i < nfirstpos[-1]; ++i)
  1159.     insert(firstpos[i], &merged);
  1160.   epsclosure(&merged, r);
  1161.  
  1162.   /* Check if any of the positions of state 0 will want newline context. */
  1163.   wants_newline = 0;
  1164.   for (i = 0; i < merged.nelem; ++i)
  1165.     if (_PREV_NEWLINE_DEPENDENT(merged.elems[i].constraint))
  1166.       wants_newline = 1;
  1167.  
  1168.   /* Build the initial state. */
  1169.   r->salloc = 1;
  1170.   r->sindex = 0;
  1171.   MALLOC(r->states, _dfa_state, r->salloc);
  1172.   state_index(r, &merged, wants_newline, 0);
  1173.  
  1174.   free(o_nullable);
  1175.   free(o_nfirst);
  1176.   free(o_firstpos);
  1177.   free(o_nlast);
  1178.   free(o_lastpos);
  1179.   free(nalloc);
  1180.   free(merged.elems);
  1181. }
  1182.  
  1183. /* Find, for each character, the transition out of state s of r, and store
  1184.    it in the appropriate slot of trans.
  1185.  
  1186.    We divide the positions of s into groups (positions can appear in more
  1187.    than one group).  Each group is labeled with a set of characters that
  1188.    every position in the group matches (taking into account, if necessary,
  1189.    preceding context information of s).  For each group, find the union
  1190.    of the its elements' follows.  This set is the set of positions of the
  1191.    new state.  For each character in the group's label, set the transition
  1192.    on this character to be to a state corresponding to the set's positions,
  1193.    and its associated backward context information, if necessary.
  1194.  
  1195.    If we are building a searching matcher, we include the positions of state
  1196.    0 in every state.
  1197.  
  1198.    The collection of groups is constructed by building an equivalence-class
  1199.    partition of the positions of s.
  1200.  
  1201.    For each position, find the set of characters C that it matches.  Eliminate
  1202.    any characters from C that fail on grounds of backward context.
  1203.  
  1204.    Search through the groups, looking for a group whose label L has nonempty
  1205.    intersection with C.  If L - C is nonempty, create a new group labeled
  1206.    L - C and having the same positions as the current group, and set L to
  1207.    the intersection of L and C.  Insert the position in this group, set
  1208.    C = C - L, and resume scanning.
  1209.  
  1210.    If after comparing with every group there are characters remaining in C,
  1211.    create a new group labeled with the characters of C and insert this
  1212.    position in that group. */
  1213. void
  1214. regstate(s, r, trans)
  1215.      int s;
  1216.      struct regexp *r;
  1217.      int trans[];
  1218. {
  1219.   _position_set grps[_NOTCHAR];    /* As many as will ever be needed. */
  1220.   _charset labels[_NOTCHAR];    /* Labels corresponding to the groups. */
  1221.   int ngrps = 0;        /* Number of groups actually used. */
  1222.   _position pos;        /* Current position being considered. */
  1223.   _charset matches;        /* Set of matching characters. */
  1224.   int matchesf;            /* True if matches is nonempty. */
  1225.   _charset intersect;        /* Intersection with some label set. */
  1226.   int intersectf;        /* True if intersect is nonempty. */
  1227.   _charset leftovers;        /* Stuff in the label that didn't match. */
  1228.   int leftoversf;        /* True if leftovers is nonempty. */
  1229.   static _charset letters;    /* Set of characters considered letters. */
  1230.   static _charset newline;    /* Set of characters that aren't newline. */
  1231.   _position_set follows;    /* Union of the follows of some group. */
  1232.   _position_set tmp;        /* Temporary space for merging sets. */
  1233.   int state;            /* New state. */
  1234.   int wants_newline;        /* New state wants to know newline context. */
  1235.   int state_newline;        /* New state on a newline transition. */
  1236.   int wants_letter;        /* New state wants to know letter context. */
  1237.   int state_letter;        /* New state on a letter transition. */
  1238.   static initialized;        /* Flag for static initialization. */
  1239.   int i, j, k;
  1240.  
  1241.   /* Initialize the set of letters, if necessary. */
  1242.   if (! initialized)
  1243.     {
  1244.       initialized = 1;
  1245.       for (i = 0; i < _NOTCHAR; ++i)
  1246.     if (ISALNUM(i))
  1247.       setbit(i, letters);
  1248.       setbit('\n', newline);
  1249.     }
  1250.  
  1251.   zeroset(matches);
  1252.  
  1253.   for (i = 0; i < r->states[s].elems.nelem; ++i)
  1254.     {
  1255.       pos = r->states[s].elems.elems[i];
  1256.       if (r->tokens[pos.index] >= 0 && r->tokens[pos.index] < _NOTCHAR)
  1257.     setbit(r->tokens[pos.index], matches);
  1258.       else if (r->tokens[pos.index] >= _SET)
  1259.     copyset(r->charsets[r->tokens[pos.index] - _SET], matches);
  1260.       else
  1261.     continue;
  1262.  
  1263.       /* Some characters may need to be eliminated from matches because
  1264.      they fail in the current context. */
  1265.       if (pos.constraint != 0xFF)
  1266.     {
  1267.       if (! _MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1268.                      r->states[s].newline, 1))
  1269.         clrbit('\n', matches);
  1270.       if (! _MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1271.                      r->states[s].newline, 0))
  1272.         for (j = 0; j < _CHARSET_INTS; ++j)
  1273.           matches[j] &= newline[j];
  1274.       if (! _MATCHES_LETTER_CONTEXT(pos.constraint,
  1275.                     r->states[s].letter, 1))
  1276.         for (j = 0; j < _CHARSET_INTS; ++j)
  1277.           matches[j] &= ~letters[j];
  1278.       if (! _MATCHES_LETTER_CONTEXT(pos.constraint,
  1279.                     r->states[s].letter, 0))
  1280.         for (j = 0; j < _CHARSET_INTS; ++j)
  1281.           matches[j] &= letters[j];
  1282.  
  1283.       /* If there are no characters left, there's no point in going on. */
  1284.       for (j = 0; j < _CHARSET_INTS && !matches[j]; ++j)
  1285.         ;
  1286.       if (j == _CHARSET_INTS)
  1287.         continue;
  1288.     }
  1289.  
  1290.       for (j = 0; j < ngrps; ++j)
  1291.     {
  1292.       /* If matches contains a single character only, and the current
  1293.          group's label doesn't contain that character, go on to the
  1294.          next group. */
  1295.       if (r->tokens[pos.index] >= 0 && r->tokens[pos.index] < _NOTCHAR
  1296.           && !tstbit(r->tokens[pos.index], labels[j]))
  1297.         continue;
  1298.  
  1299.       /* Check if this group's label has a nonempty intersection with
  1300.          matches. */
  1301.       intersectf = 0;
  1302.       for (k = 0; k < _CHARSET_INTS; ++k)
  1303.         (intersect[k] = matches[k] & labels[j][k]) ? intersectf = 1 : 0;
  1304.       if (! intersectf)
  1305.         continue;
  1306.  
  1307.       /* It does; now find the set differences both ways. */
  1308.       leftoversf = matchesf = 0;
  1309.       for (k = 0; k < _CHARSET_INTS; ++k)
  1310.         {
  1311.           /* Even an optimizing compiler can't know this for sure. */
  1312.           int match = matches[k], label = labels[j][k];
  1313.  
  1314.           (leftovers[k] = ~match & label) ? leftoversf = 1 : 0;
  1315.           (matches[k] = match & ~label) ? matchesf = 1 : 0;
  1316.         }
  1317.  
  1318.       /* If there were leftovers, create a new group labeled with them. */
  1319.       if (leftoversf)
  1320.         {
  1321.           copyset(leftovers, labels[ngrps]);
  1322.           copyset(intersect, labels[j]);
  1323.           MALLOC(grps[ngrps].elems, _position, r->nleaves);
  1324.           copy(&grps[j], &grps[ngrps]);
  1325.           ++ngrps;
  1326.         }
  1327.  
  1328.       /* Put the position in the current group.  Note that there is no
  1329.          reason to call insert() here. */
  1330.       grps[j].elems[grps[j].nelem++] = pos;
  1331.  
  1332.       /* If every character matching the current position has been
  1333.          accounted for, we're done. */
  1334.       if (! matchesf)
  1335.         break;
  1336.     }
  1337.  
  1338.       /* If we've passed the last group, and there are still characters
  1339.      unaccounted for, then we'll have to create a new group. */
  1340.       if (j == ngrps)
  1341.     {
  1342.       copyset(matches, labels[ngrps]);
  1343.       zeroset(matches);
  1344.       MALLOC(grps[ngrps].elems, _position, r->nleaves);
  1345.       grps[ngrps].nelem = 1;
  1346.       grps[ngrps].elems[0] = pos;
  1347.       ++ngrps;
  1348.     }
  1349.     }
  1350.  
  1351.   MALLOC(follows.elems, _position, r->nleaves);
  1352.   MALLOC(tmp.elems, _position, r->nleaves);
  1353.  
  1354.   /* If we are a searching matcher, the default transition is to a state
  1355.      containing the positions of state 0, otherwise the default transition
  1356.      is to fail miserably. */
  1357.   if (r->searchflag)
  1358.     {
  1359.       wants_newline = 0;
  1360.       wants_letter = 0;
  1361.       for (i = 0; i < r->states[0].elems.nelem; ++i)
  1362.     {
  1363.       if (_PREV_NEWLINE_DEPENDENT(r->states[0].elems.elems[i].constraint))
  1364.         wants_newline = 1;
  1365.       if (_PREV_LETTER_DEPENDENT(r->states[0].elems.elems[i].constraint))
  1366.         wants_letter = 1;
  1367.     }
  1368.       copy(&r->states[0].elems, &follows);
  1369.       state = state_index(r, &follows, 0, 0);
  1370.       if (wants_newline)
  1371.     state_newline = state_index(r, &follows, 1, 0);
  1372.       else
  1373.     state_newline = state;
  1374.       if (wants_letter)
  1375.     state_letter = state_index(r, &follows, 0, 1);
  1376.       else
  1377.     state_letter = state;
  1378.       for (i = 0; i < _NOTCHAR; ++i)
  1379.     if (i == '\n')
  1380.       trans[i] = state_newline;
  1381.     else if (ISALNUM(i))
  1382.       trans[i] = state_letter;
  1383.     else
  1384.       trans[i] = state;
  1385.     }
  1386.   else
  1387.     for (i = 0; i < _NOTCHAR; ++i)
  1388.       trans[i] = -1;
  1389.  
  1390.   for (i = 0; i < ngrps; ++i)
  1391.     {
  1392.       follows.nelem = 0;
  1393.  
  1394.       /* Find the union of the follows of the positions of the group.
  1395.      This is a hideously inefficient loop.  Fix it someday. */
  1396.       for (j = 0; j < grps[i].nelem; ++j)
  1397.     for (k = 0; k < r->follows[grps[i].elems[j].index].nelem; ++k)
  1398.       insert(r->follows[grps[i].elems[j].index].elems[k], &follows);
  1399.  
  1400.       /* If we are building a searching matcher, throw in the positions
  1401.      of state 0 as well. */
  1402.       if (r->searchflag)
  1403.     for (j = 0; j < r->states[0].elems.nelem; ++j)
  1404.       insert(r->states[0].elems.elems[j], &follows);
  1405.  
  1406.       /* Find out if the new state will want any context information. */
  1407.       wants_newline = 0;
  1408.       if (tstbit('\n', labels[i]))
  1409.     for (j = 0; j < follows.nelem; ++j)
  1410.       if (_PREV_NEWLINE_DEPENDENT(follows.elems[j].constraint))
  1411.         wants_newline = 1;
  1412.  
  1413.       wants_letter = 0;
  1414.       for (j = 0; j < _CHARSET_INTS; ++j)
  1415.     if (labels[i][j] & letters[j])
  1416.       break;
  1417.       if (j < _CHARSET_INTS)
  1418.     for (j = 0; j < follows.nelem; ++j)
  1419.       if (_PREV_LETTER_DEPENDENT(follows.elems[j].constraint))
  1420.         wants_letter = 1;
  1421.  
  1422.       /* Find the state(s) corresponding to the union of the follows. */
  1423.       state = state_index(r, &follows, 0, 0);
  1424.       if (wants_newline)
  1425.     state_newline = state_index(r, &follows, 1, 0);
  1426.       else
  1427.     state_newline = state;
  1428.       if (wants_letter)
  1429.     state_letter = state_index(r, &follows, 0, 1);
  1430.       else
  1431.     state_letter = state;
  1432.  
  1433.       /* Set the transitions for each character in the current label. */
  1434.       for (j = 0; j < _CHARSET_INTS; ++j)
  1435.     for (k = 0; k < INTBITS; ++k)
  1436.       if (labels[i][j] & 1 << k)
  1437.         {
  1438.           int c = j * INTBITS + k;
  1439.  
  1440.           if (c == '\n')
  1441.         trans[c] = state_newline;
  1442.           else if (ISALNUM(c))
  1443.         trans[c] = state_letter;
  1444.           else if (c < _NOTCHAR)
  1445.         trans[c] = state;
  1446.         }
  1447.     }
  1448.  
  1449.   for (i = 0; i < ngrps; ++i)
  1450.     free(grps[i].elems);
  1451.   free(follows.elems);
  1452.   free(tmp.elems);
  1453. }
  1454.  
  1455. /* Some routines for manipulating a compiled regexp's transition tables.
  1456.    Each state may or may not have a transition table; if it does, and it
  1457.    is a non-accepting state, then r->trans[state] points to its table.
  1458.    If it is an accepting state then r->fails[state] points to its table.
  1459.    If it has no table at all, then r->trans[state] is NULL.
  1460.    TODO: Improve this comment, get rid of the unnecessary redundancy. */
  1461.  
  1462. static void
  1463. build_state(s, r)
  1464.      int s;
  1465.      struct regexp *r;
  1466. {
  1467.   int *trans;            /* The new transition table. */
  1468.   int i;
  1469.  
  1470.   /* Set an upper limit on the number of transition tables that will ever
  1471.      exist at once.  1024 is arbitrary.  The idea is that the frequently
  1472.      used transition tables will be quickly rebuilt, whereas the ones that
  1473.      were only needed once or twice will be cleared away. */
  1474.   if (r->trcount >= 1024)
  1475.     {
  1476.       for (i = 0; i < r->tralloc; ++i)
  1477.     if (r->trans[i])
  1478.       {
  1479.         free((ptr_t) r->trans[i]);
  1480.         r->trans[i] = NULL;
  1481.       }
  1482.     else if (r->fails[i])
  1483.       {
  1484.         free((ptr_t) r->fails[i]);
  1485.         r->fails[i] = NULL;
  1486.       }
  1487.       r->trcount = 0;
  1488.     }
  1489.  
  1490.   ++r->trcount;
  1491.  
  1492.   /* Set up the success bits for this state. */
  1493.   r->success[s] = 0;
  1494.   if (ACCEPTS_IN_CONTEXT(r->states[s].newline, 1, r->states[s].letter, 0,
  1495.       s, *r))
  1496.     r->success[s] |= 4;
  1497.   if (ACCEPTS_IN_CONTEXT(r->states[s].newline, 0, r->states[s].letter, 1,
  1498.       s, *r))
  1499.     r->success[s] |= 2;
  1500.   if (ACCEPTS_IN_CONTEXT(r->states[s].newline, 0, r->states[s].letter, 0,
  1501.       s, *r))
  1502.     r->success[s] |= 1;
  1503.  
  1504.   MALLOC(trans, int, _NOTCHAR);
  1505.   regstate(s, r, trans);
  1506.  
  1507.   /* Now go through the new transition table, and make sure that the trans
  1508.      and fail arrays are allocated large enough to hold a pointer for the
  1509.      largest state mentioned in the table. */
  1510.   for (i = 0; i < _NOTCHAR; ++i)
  1511.     if (trans[i] >= r->tralloc)
  1512.       {
  1513.     int oldalloc = r->tralloc;
  1514.  
  1515.     while (trans[i] >= r->tralloc)
  1516.       r->tralloc *= 2;
  1517.     REALLOC(r->realtrans, int *, r->tralloc + 1);
  1518.     r->trans = r->realtrans + 1;
  1519.     REALLOC(r->fails, int *, r->tralloc);
  1520.     REALLOC(r->success, int, r->tralloc);
  1521.     REALLOC(r->newlines, int, r->tralloc);
  1522.     while (oldalloc < r->tralloc)
  1523.       {
  1524.         r->trans[oldalloc] = NULL;
  1525.         r->fails[oldalloc++] = NULL;
  1526.       }
  1527.       }
  1528.  
  1529.   /* Keep the newline transition in a special place so we can use it as
  1530.      a sentinel. */
  1531.   r->newlines[s] = trans['\n'];
  1532.   trans['\n'] = -1;
  1533.  
  1534.   if (ACCEPTING(s, *r))
  1535.     r->fails[s] = trans;
  1536.   else
  1537.     r->trans[s] = trans;
  1538. }
  1539.  
  1540. static void
  1541. build_state_zero(r)
  1542.      struct regexp *r;
  1543. {
  1544.   r->tralloc = 1;
  1545.   r->trcount = 0;
  1546.   CALLOC(r->realtrans, int *, r->tralloc + 1);
  1547.   r->trans = r->realtrans + 1;
  1548.   CALLOC(r->fails, int *, r->tralloc);
  1549.   MALLOC(r->success, int, r->tralloc);
  1550.   MALLOC(r->newlines, int, r->tralloc);
  1551.   build_state(0, r);
  1552. }
  1553.  
  1554. /* Search through a buffer looking for a match to the given struct regexp.
  1555.    Find the first occurrence of a string matching the regexp in the buffer,
  1556.    and the shortest possible version thereof.  Return a pointer to the first
  1557.    character after the match, or NULL if none is found.  Begin points to
  1558.    the beginning of the buffer, and end points to the first character after
  1559.    its end.  We store a newline in *end to act as a sentinel, so end had
  1560.    better point somewhere valid.  Newline is a flag indicating whether to
  1561.    allow newlines to be in the matching string.  If count is non-
  1562.    NULL it points to a place we're supposed to increment every time we
  1563.    see a newline.  Finally, if backref is non-NULL it points to a place
  1564.    where we're supposed to store a 1 if backreferencing happened and the
  1565.    match needs to be verified by a backtracking matcher.  Otherwise
  1566.    we store a 0 in *backref. */
  1567. char *
  1568. regexecute(r, begin, end, newline, count, backref)
  1569.      struct regexp *r;
  1570.      char *begin;
  1571.      char *end;
  1572.      int newline;
  1573.      int *count;
  1574.      int *backref;
  1575. {
  1576.   register s, s1, tmp;        /* Current state. */
  1577.   register unsigned char *p;    /* Current input character. */
  1578.   register **trans, *t;        /* Copy of r->trans so it can be optimized
  1579.                    into a register. */
  1580.   static sbit[_NOTCHAR];    /* Table for anding with r->success. */
  1581.   static sbit_init;
  1582.  
  1583.   if (! sbit_init)
  1584.     {
  1585.       int i;
  1586.  
  1587.       sbit_init = 1;
  1588.       for (i = 0; i < _NOTCHAR; ++i)
  1589.     if (i == '\n')
  1590.       sbit[i] = 4;
  1591.     else if (ISALNUM(i))
  1592.       sbit[i] = 2;
  1593.     else
  1594.       sbit[i] = 1;
  1595.     }
  1596.  
  1597.   if (! r->tralloc)
  1598.     build_state_zero(r);
  1599.  
  1600.   s = 0;
  1601.   p = (unsigned char *) begin;
  1602.   trans = r->trans;
  1603.   *end = '\n';
  1604.  
  1605.   for (;;)
  1606.     {
  1607.       /* The dreaded inner loop. */
  1608.       if (t = trans[s])
  1609.     do
  1610.       {
  1611.         s1 = t[*p++];
  1612.         if (! (t = trans[s1]))
  1613.           goto last_was_s;
  1614.         s = t[*p++];
  1615.       }
  1616.         while (t = trans[s]);
  1617.       goto last_was_s1;
  1618.     last_was_s:
  1619.       tmp = s, s = s1, s1 = tmp;
  1620.     last_was_s1:
  1621.  
  1622.       if (s >= 0 && p <= (unsigned char *) end && r->fails[s])
  1623.     {
  1624.       if (r->success[s] & sbit[*p])
  1625.         {
  1626.           if (backref)
  1627.         if (r->states[s].backref)
  1628.           *backref = 1;
  1629.         else
  1630.           *backref = 0;
  1631.           return (char *) p;
  1632.         }
  1633.  
  1634.       s1 = s;
  1635.       s = r->fails[s][*p++];
  1636.       continue;
  1637.     }
  1638.  
  1639.       /* If the previous character was a newline, count it. */
  1640.       if (count && (char *) p <= end && p[-1] == '\n')
  1641.     ++*count;
  1642.  
  1643.       /* Check if we've run off the end of the buffer. */
  1644.       if ((char *) p >= end)
  1645.     return NULL;
  1646.  
  1647.       if (s >= 0)
  1648.     {
  1649.       build_state(s, r);
  1650.       trans = r->trans;
  1651.       continue;
  1652.     }
  1653.  
  1654.       if (p[-1] == '\n' && newline)
  1655.     {
  1656.       s = r->newlines[s1];
  1657.       continue;
  1658.     }
  1659.  
  1660.       s = 0;
  1661.     }
  1662. }
  1663.  
  1664. /* Initialize the components of a regexp that the other routines don't
  1665.    initialize for themselves. */
  1666. void
  1667. reginit(r)
  1668.      struct regexp *r;
  1669. {
  1670.   r->calloc = 1;
  1671.   MALLOC(r->charsets, _charset, r->calloc);
  1672.   r->cindex = 0;
  1673.  
  1674.   r->talloc = 1;
  1675.   MALLOC(r->tokens, _token, r->talloc);
  1676.   r->tindex = r->depth = r->nleaves = r->nregexps = 0;
  1677.  
  1678.   r->searchflag = 0;
  1679.   r->tralloc = 0;
  1680. }
  1681.  
  1682. /* Parse and analyze a single string of the given length. */
  1683. void
  1684. regcompile(s, len, r, searchflag)
  1685.      const char *s;
  1686.      size_t len;
  1687.      struct regexp *r;
  1688.      int searchflag;
  1689. {
  1690.   if (case_fold)    /* dummy folding in service of regmust() */
  1691.     {
  1692.       char *copy;
  1693.       int i;
  1694.  
  1695.       copy = malloc(len);
  1696.       if (!copy)
  1697.     regerror("out of memory");
  1698.       
  1699.       /* This is a complete kludge and could potentially break
  1700.      \<letter> escapes . . . */
  1701.       case_fold = 0;
  1702.       for (i = 0; i < len; ++i)
  1703.     if (ISUPPER(s[i]))
  1704.       copy[i] = tolower(s[i]);
  1705.     else
  1706.       copy[i] = s[i];
  1707.  
  1708.       reginit(r);
  1709.       r->mustn = 0;
  1710.       r->must[0] = '\0';
  1711.       regparse(copy, len, r);
  1712.       free(copy);
  1713.       regmust(r);
  1714.       reganalyze(r, searchflag);
  1715.       case_fold = 1;
  1716.       reginit(r);
  1717.       regparse(s, len, r);
  1718.       reganalyze(r, searchflag);
  1719.     }
  1720.   else
  1721.     {
  1722.         reginit(r);
  1723.         regparse(s, len, r);
  1724.         regmust(r);
  1725.         reganalyze(r, searchflag);
  1726.     }
  1727. }
  1728.  
  1729. /* Free the storage held by the components of a regexp. */
  1730. void
  1731. regfree(r)
  1732.      struct regexp *r;
  1733. {
  1734.   int i;
  1735.  
  1736.   free((ptr_t) r->charsets);
  1737.   free((ptr_t) r->tokens);
  1738.   for (i = 0; i < r->sindex; ++i)
  1739.     free((ptr_t) r->states[i].elems.elems);
  1740.   free((ptr_t) r->states);
  1741.   for (i = 0; i < r->tindex; ++i)
  1742.     if (r->follows[i].elems)
  1743.       free((ptr_t) r->follows[i].elems);
  1744.   free((ptr_t) r->follows);
  1745.   for (i = 0; i < r->tralloc; ++i)
  1746.     if (r->trans[i])
  1747.       free((ptr_t) r->trans[i]);
  1748.     else if (r->fails[i])
  1749.       free((ptr_t) r->fails[i]);
  1750.   free((ptr_t) r->realtrans);
  1751.   free((ptr_t) r->fails);
  1752.   free((ptr_t) r->newlines);
  1753. }
  1754.  
  1755. /*
  1756. Having found the postfix representation of the regular expression,
  1757. try to find a long sequence of characters that must appear in any line
  1758. containing the r.e.
  1759. Finding a "longest" sequence is beyond the scope here;
  1760. we take an easy way out and hope for the best.
  1761. (Take "(ab|a)b"--please.)
  1762.  
  1763. We do a bottom-up calculation of sequences of characters that must appear
  1764. in matches of r.e.'s represented by trees rooted at the nodes of the postfix
  1765. representation:
  1766.     sequences that must appear at the left of the match ("left")
  1767.     sequences that must appear at the right of the match ("right")
  1768.     lists of sequences that must appear somewhere in the match ("in")
  1769.     sequences that must constitute the match ("is")
  1770. When we get to the root of the tree, we use one of the longest of its
  1771. calculated "in" sequences as our answer.  The sequence we find is returned in
  1772. r->must (where "r" is the single argument passed to "regmust");
  1773. the length of the sequence is returned in r->mustn.
  1774.  
  1775. The sequences calculated for the various types of node (in pseudo ANSI c)
  1776. are shown below.  "p" is the operand of unary operators (and the left-hand
  1777. operand of binary operators); "q" is the right-hand operand of binary operators
  1778. .
  1779. "ZERO" means "a zero-length sequence" below.
  1780.  
  1781. Type    left        right        is        in
  1782. ----    ----        -----        --        --
  1783. char c    # c        # c        # c        # c
  1784.  
  1785. SET    ZERO        ZERO        ZERO        ZERO
  1786.  
  1787. STAR    ZERO        ZERO        ZERO        ZERO
  1788.  
  1789. QMARK    ZERO        ZERO        ZERO        ZERO
  1790.  
  1791. PLUS    p->left        p->right    ZERO        p->in
  1792.  
  1793. CAT    (p->is==ZERO)?    (q->is==ZERO)?    (p->is!=ZERO &&    p->in plus
  1794.     p->left :    q->right :    q->is!=ZERO) ?    q->in plus
  1795.     p->is##q->left    p->right##q->is    p->is##q->is :    p->right##q->left
  1796.                     ZERO
  1797.  
  1798. OR    longest common    longest common    (do p->is and    substrings common to
  1799.     leading        trailing    q->is have same    p->in and q->in
  1800.     (sub)sequence    (sub)sequence    length and    
  1801.     of p->left    of p->right    content) ?    
  1802.     and q->left    and q->right    p->is : NULL    
  1803.  
  1804. If there's anything else we recognize in the tree, all four sequences get set
  1805. to zero-length sequences.  If there's something we don't recognize in the tree,
  1806. we just return a zero-length sequence.
  1807.  
  1808. Break ties in favor of infrequent letters (choosing 'zzz' in preference to
  1809. 'aaa')?
  1810.  
  1811. And. . .is it here or someplace that we might ponder "optimizations" such as
  1812.     egrep 'psi|epsilon'    ->    egrep 'psi'
  1813.     egrep 'pepsi|epsilon'    ->    egrep 'epsi'
  1814.                     (Yes, we now find "epsi" as a "string
  1815.                     that must occur", but we might also
  1816.                     simplify the *entire* r.e. being sought
  1817. )
  1818.     grep '[c]'        ->    grep 'c'
  1819.     grep '(ab|a)b'        ->    grep 'ab'
  1820.     grep 'ab*'        ->    grep 'a'
  1821.     grep 'a*b'        ->    grep 'b'
  1822. There are several issues:
  1823.     Is optimization easy (enough)?
  1824.  
  1825.     Does optimization actually accomplish anything,
  1826.     or is the automaton you get from "psi|epsilon" (for example)
  1827.     the same as the one you get from "psi" (for example)?
  1828.  
  1829.     Are optimizable r.e.'s likely to be used in real-life situations
  1830.     (something like 'ab*' is probably unlikely; something like is
  1831.     'psi|epsilon' is likelier)?
  1832. */
  1833.  
  1834. static char *
  1835. icatalloc(old, new)
  1836. char *    old;
  1837. char *    new;
  1838. {
  1839.     register char *    result;
  1840.     register int    oldsize, newsize;
  1841.  
  1842.     newsize = (new == NULL) ? 0 : strlen(new);
  1843.     if (old == NULL)
  1844.         oldsize = 0;
  1845.     else if (newsize == 0)
  1846.         return old;
  1847.     else    oldsize = strlen(old);
  1848.     if (old == NULL)
  1849.         result = (char *) malloc(newsize + 1);
  1850.     else    result = (char *) realloc((void *) old, oldsize + newsize + 1);
  1851.     if (result != NULL && new != NULL)
  1852.         (void) strcpy(result + oldsize, new);
  1853.     return result;
  1854. }
  1855.  
  1856. static char *
  1857. icpyalloc(string)
  1858. const char *    string;
  1859. {
  1860.     return icatalloc((char *) NULL, string);
  1861. }
  1862.  
  1863. static char *
  1864. istrstr(lookin, lookfor)
  1865. char *        lookin;
  1866. register char *    lookfor;
  1867. {
  1868.     register char *    cp;
  1869.     register int    len;
  1870.  
  1871.     len = strlen(lookfor);
  1872.     for (cp = lookin; *cp != '\0'; ++cp)
  1873.         if (strncmp(cp, lookfor, len) == 0)
  1874.             return cp;
  1875.     return NULL;
  1876. }
  1877.  
  1878. static void
  1879. ifree(cp)
  1880. char *    cp;
  1881. {
  1882.     if (cp != NULL)
  1883.         free(cp);
  1884. }
  1885.  
  1886. static void
  1887. freelist(cpp)
  1888. register char **    cpp;
  1889. {
  1890.     register int    i;
  1891.  
  1892.     if (cpp == NULL)
  1893.         return;
  1894.     for (i = 0; cpp[i] != NULL; ++i) {
  1895.         free(cpp[i]);
  1896.         cpp[i] = NULL;
  1897.     }
  1898. }
  1899.  
  1900. static char **
  1901. enlist(cpp, new, len)
  1902. register char **    cpp;
  1903. register char *        new;
  1904. int len;
  1905. {
  1906.     register int    i, j;
  1907.  
  1908.     if (cpp == NULL)
  1909.         return NULL;
  1910.     if ((new = icpyalloc(new)) == NULL) {
  1911.         freelist(cpp);
  1912.         return NULL;
  1913.     }
  1914.     new[len] = '\0';
  1915.     /*
  1916.     ** Is there already something in the list that's new (or longer)?
  1917.     */
  1918.     for (i = 0; cpp[i] != NULL; ++i)
  1919.         if (istrstr(cpp[i], new) != NULL) {
  1920.             free(new);
  1921.             return cpp;
  1922.         }
  1923.     /*
  1924.     ** Eliminate any obsoleted strings.
  1925.     */
  1926.     j = 0;
  1927.     while (cpp[j] != NULL)
  1928.         if (istrstr(new, cpp[j]) == NULL)
  1929.             ++j;
  1930.         else {
  1931.             free(cpp[j]);
  1932.             if (--i == j)
  1933.                 break;
  1934.             cpp[j] = cpp[i];
  1935.         }
  1936.     /*
  1937.     ** Add the new string.
  1938.     */
  1939.     cpp = (char **) realloc((char *) cpp, (i + 2) * sizeof *cpp);
  1940.     if (cpp == NULL)
  1941.         return NULL;
  1942.     cpp[i] = new;
  1943.     cpp[i + 1] = NULL;
  1944.     return cpp;
  1945. }
  1946.  
  1947. /*
  1948. ** Given pointers to two strings,
  1949. ** return a pointer to an allocated list of their distinct common substrings.
  1950. ** Return NULL if something seems wild.
  1951. */
  1952.  
  1953. static char **
  1954. comsubs(left, right)
  1955. char *    left;
  1956. char *    right;
  1957. {
  1958.     register char **    cpp;
  1959.     register char *        lcp;
  1960.     register char *        rcp;
  1961.     register int        i, len;
  1962.  
  1963.     if (left == NULL || right == NULL)
  1964.         return NULL;
  1965.     cpp = (char **) malloc(sizeof *cpp);
  1966.     if (cpp == NULL)
  1967.         return NULL;
  1968.     cpp[0] = NULL;
  1969.     for (lcp = left; *lcp != '\0'; ++lcp) {
  1970.         len = 0;
  1971.         rcp = index(right, *lcp);
  1972.         while (rcp != NULL) {
  1973.             for (i = 1; lcp[i] != '\0' && lcp[i] == rcp[i]; ++i)
  1974.                 ;
  1975.             if (i > len)
  1976.                 len = i;
  1977.             rcp = index(rcp + 1, *lcp);
  1978.         }
  1979.         if (len == 0)
  1980.             continue;
  1981.         if ((cpp = enlist(cpp, lcp, len)) == NULL)
  1982.             break;
  1983.     }
  1984.     return cpp;
  1985. }
  1986.  
  1987. static char **
  1988. addlists(old, new)
  1989. char **    old;
  1990. char **    new;
  1991. {
  1992.     register int    i;
  1993.  
  1994.     if (old == NULL || new == NULL)
  1995.         return NULL;
  1996.     for (i = 0; new[i] != NULL; ++i) {
  1997.         old = enlist(old, new[i], strlen(new[i]));
  1998.         if (old == NULL)
  1999.             break;
  2000.     }
  2001.     return old;
  2002. }
  2003.  
  2004. /*
  2005. ** Given two lists of substrings,
  2006. ** return a new list giving substrings common to both.
  2007. */
  2008.  
  2009. static char **
  2010. inboth(left, right)
  2011. char **    left;
  2012. char **    right;
  2013. {
  2014.     register char **    both;
  2015.     register char **    temp;
  2016.     register int        lnum, rnum;
  2017.  
  2018.     if (left == NULL || right == NULL)
  2019.         return NULL;
  2020.     both = (char **) malloc(sizeof *both);
  2021.     if (both == NULL)
  2022.         return NULL;
  2023.     both[0] = NULL;
  2024.     for (lnum = 0; left[lnum] != NULL; ++lnum) {
  2025.         for (rnum = 0; right[rnum] != NULL; ++rnum) {
  2026.             temp = comsubs(left[lnum], right[rnum]);
  2027.             if (temp == NULL) {
  2028.                 freelist(both);
  2029.                 return NULL;
  2030.             }
  2031.             both = addlists(both, temp);
  2032.             freelist(temp);
  2033.             if (both == NULL)
  2034.                 return NULL;
  2035.         }
  2036.     }
  2037.     return both;
  2038. }
  2039.  
  2040. typedef struct {
  2041.     char **    in;
  2042.     char *    left;
  2043.     char *    right;
  2044.     char *    is;
  2045. } must;
  2046.  
  2047. static void
  2048. resetmust(mp)
  2049. register must *    mp;
  2050. {
  2051.     mp->left[0] = mp->right[0] = mp->is[0] = '\0';
  2052.     freelist(mp->in);
  2053. }
  2054.  
  2055. static void
  2056. regmust(reg)
  2057. register struct regexp *    reg;
  2058. {
  2059.     register must *        musts;
  2060.     register must *        mp;
  2061.     register char *        result;
  2062.     register int        ri;
  2063.     register int        i;
  2064.     register _token        t;
  2065.     static must        must0;
  2066.  
  2067.     reg->mustn = 0;
  2068.     reg->must[0] = '\0';
  2069.     musts = (must *) malloc((reg->tindex + 1) * sizeof *musts);
  2070.     if (musts == NULL)
  2071.         return;
  2072.     mp = musts;
  2073.     for (i = 0; i <= reg->tindex; ++i)
  2074.         mp[i] = must0;
  2075.     for (i = 0; i <= reg->tindex; ++i) {
  2076.         mp[i].in = (char **) malloc(sizeof *mp[i].in);
  2077.         mp[i].left = malloc(2);
  2078.         mp[i].right = malloc(2);
  2079.         mp[i].is = malloc(2);
  2080.         if (mp[i].in == NULL || mp[i].left == NULL ||
  2081.             mp[i].right == NULL || mp[i].is == NULL)
  2082.                 goto done;
  2083.         mp[i].left[0] = mp[i].right[0] = mp[i].is[0] = '\0';
  2084.         mp[i].in[0] = NULL;
  2085.     }
  2086.     result = "";
  2087. #ifdef DEBUG
  2088.     fprintf(stderr, "regmust:\n");
  2089.     for (i = 0; i < reg->tindex; ++i) {
  2090.         fprintf(stderr, " %d:", i);
  2091.         prtok(reg->tokens[i]);
  2092.     }
  2093.     putc('\n', stderr);
  2094. #endif
  2095.     for (ri = 0; ri < reg->tindex; ++ri) {
  2096.         switch (t = reg->tokens[ri]) {
  2097.         case _ALLBEGLINE:
  2098.         case _ALLENDLINE:
  2099.         case _LPAREN:
  2100.         case _RPAREN:
  2101.             goto done;        /* "cannot happen" */
  2102.         case _EMPTY:
  2103.         case _BEGLINE:
  2104.         case _ENDLINE:
  2105.         case _BEGWORD:
  2106.         case _ENDWORD:
  2107.         case _LIMWORD:
  2108.         case _NOTLIMWORD:
  2109.         case _BACKREF:
  2110.             resetmust(mp);
  2111.             break;
  2112.         case _STAR:
  2113.         case _QMARK:
  2114.             if (mp <= musts)
  2115.                 goto done;    /* "cannot happen" */
  2116.             --mp;
  2117.             resetmust(mp);
  2118.             break;
  2119.         case _OR:
  2120.             if (mp < &musts[2])
  2121.                 goto done;    /* "cannot happen" */
  2122.             {
  2123.                 register char **    new;
  2124.                 register must *        lmp;
  2125.                 register must *        rmp;
  2126.                 register int        j, ln, rn, n;
  2127.  
  2128.                 rmp = --mp;
  2129.                 lmp = --mp;
  2130.                 /* Guaranteed to be.  Unlikely, but. . . */
  2131.                 if (strcmp(lmp->is, rmp->is) != 0)
  2132.                     lmp->is[0] = '\0';
  2133.                 /* Left side--easy */
  2134.                 i = 0;
  2135.                 while (lmp->left[i] != '\0' &&
  2136.                     lmp->left[i] == rmp->left[i])
  2137.                         ++i;
  2138.                 lmp->left[i] = '\0';
  2139.                 /* Right side */
  2140.                 ln = strlen(lmp->right);
  2141.                 rn = strlen(rmp->right);
  2142.                 n = ln;
  2143.                 if (n > rn)
  2144.                     n = rn;
  2145.                 for (i = 0; i < n; ++i)
  2146.                     if (lmp->right[ln - i - 1] !=
  2147.                         rmp->right[rn - i - 1])
  2148.                         break;
  2149.                 for (j = 0; j < i; ++j)
  2150.                     lmp->right[j] =
  2151.                         lmp->right[(ln - i) + j];
  2152.                 lmp->right[j] = '\0';
  2153.                 new = inboth(lmp->in, rmp->in);
  2154.                 if (new == NULL)
  2155.                     goto done;
  2156.                 freelist(lmp->in);
  2157.                 free((char *) lmp->in);
  2158.                 lmp->in = new;
  2159.             }
  2160.             break;
  2161.         case _PLUS:
  2162.             if (mp <= musts)
  2163.                 goto done;    /* "cannot happen" */
  2164.             --mp;
  2165.             mp->is[0] = '\0';
  2166.             break;
  2167.         case _END:
  2168.             if (mp != &musts[1])
  2169.                 goto done;    /* "cannot happen" */
  2170.             for (i = 0; musts[0].in[i] != NULL; ++i)
  2171.                 if (strlen(musts[0].in[i]) > strlen(result))
  2172.                     result = musts[0].in[i];
  2173.             goto done;
  2174.         case _CAT:
  2175.             if (mp < &musts[2])
  2176.                 goto done;    /* "cannot happen" */
  2177.             {
  2178.                 register must *    lmp;
  2179.                 register must *    rmp;
  2180.  
  2181.                 rmp = --mp;
  2182.                 lmp = --mp;
  2183.                 /*
  2184.                 ** In.  Everything in left, plus everything in
  2185.                 ** right, plus catenation of
  2186.                 ** left's right and right's left.
  2187.                 */
  2188.                 lmp->in = addlists(lmp->in, rmp->in);
  2189.                 if (lmp->in == NULL)
  2190.                     goto done;
  2191.                 if (lmp->right[0] != '\0' &&
  2192.                     rmp->left[0] != '\0') {
  2193.                         register char *    tp;
  2194.  
  2195.                         tp = icpyalloc(lmp->right);
  2196.                         if (tp == NULL)
  2197.                             goto done;
  2198.                         tp = icatalloc(tp, rmp->left);
  2199.                         if (tp == NULL)
  2200.                             goto done;
  2201.                         lmp->in = enlist(lmp->in, tp,
  2202.                             strlen(tp));
  2203.                         free(tp);
  2204.                         if (lmp->in == NULL)
  2205.                             goto done;
  2206.                 }
  2207.                 /* Left-hand */
  2208.                 if (lmp->is[0] != '\0') {
  2209.                     lmp->left = icatalloc(lmp->left,
  2210.                         rmp->left);
  2211.                     if (lmp->left == NULL)
  2212.                         goto done;
  2213.                 }
  2214.                 /* Right-hand */
  2215.                 if (rmp->is[0] == '\0')
  2216.                     lmp->right[0] = '\0';
  2217.                 lmp->right = icatalloc(lmp->right, rmp->right);
  2218.                 if (lmp->right == NULL)
  2219.                     goto done;
  2220.                 /* Guaranteed to be */
  2221.                 if (lmp->is[0] != '\0' && rmp->is[0] != '\0') {
  2222.                     lmp->is = icatalloc(lmp->is, rmp->is);
  2223.                     if (lmp->is == NULL)
  2224.                         goto done;
  2225.                 } else
  2226.                     lmp->is[0] = '\0';
  2227.             }
  2228.             break;
  2229.         default:
  2230.             if (t < _END) {
  2231.                 /* "cannot happen" */
  2232.                 goto done;
  2233.             } else if (t == '\0') {
  2234.                 /* not on *my* shift */
  2235.                 goto done;
  2236.             } else if (t >= _SET) {
  2237.                 /* easy enough */
  2238.                 resetmust(mp);
  2239.             } else {
  2240.                 /* plain character */
  2241.                 resetmust(mp);
  2242.                 mp->is[0] = mp->left[0] = mp->right[0] = t;
  2243.                 mp->is[1] = mp->left[1] = mp->right[1] = '\0';
  2244.                 mp->in = enlist(mp->in, mp->is, 1);
  2245.                 if (mp->in == NULL)
  2246.                     goto done;
  2247.             }
  2248.             break;
  2249.         }
  2250. #ifdef DEBUG
  2251.         fprintf(stderr, " node: %d:", ri);
  2252.         prtok(reg->tokens[ri]);
  2253.         fprintf(stderr, "\n  in:");
  2254.         for (i = 0; mp->in[i]; ++i)
  2255.             fprintf(stderr, " \"%s\"", mp->in[i]);
  2256.         fprintf(stderr, "\n  is: \"%s\"\n", mp->is);
  2257.         fprintf(stderr, "  left: \"%s\"\n", mp->left);
  2258.         fprintf(stderr, "  right: \"%s\"\n", mp->right);
  2259. #endif
  2260.         ++mp;
  2261.     }
  2262. done:
  2263.     (void) strncpy(reg->must, result, MUST_MAX - 1);
  2264.     reg->must[MUST_MAX - 1] = '\0';
  2265.     reg->mustn = strlen(reg->must);
  2266.     mp = musts;
  2267.     for (i = 0; i <= reg->tindex; ++i) {
  2268.         freelist(mp[i].in);
  2269.         ifree((char *) mp[i].in);
  2270.         ifree(mp[i].left);
  2271.         ifree(mp[i].right);
  2272.         ifree(mp[i].is);
  2273.     }
  2274.     free((char *) mp);
  2275. }
  2276.